package com.example.firstapp.network

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import com.example.firstapp.R
import okhttp3.OkHttpClient
import okhttp3.Request
import java.net.URL
import kotlin.concurrent.thread

class OkHttpActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_ok_http)
        val url = URL(intent.getStringExtra("url"))
        println(url)
        thread {
            println(11)
            try {
                val client = OkHttpClient()
                val request = Request.Builder()
                    .url(url)
                    .build()
                println(2)
                val response = client.newCall(request).execute()
                println(22)
                val responseData = response.body?.string()
                if (responseData != null) {
                    println(3)
                    showResponse(responseData)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
    private fun showResponse(res:String){
        runOnUiThread{
            val showResText: TextView = findViewById(R.id.showResText)
            showResText.text = res
        }
    }
}